package com.example.haoqisystem.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.example.haoqisystem.Utils.ConstUtil;
import com.example.haoqisystem.Utils.PageUtil;
import com.example.haoqisystem.entity.QuestionNaire;
import com.example.haoqisystem.entity.TrainningPlan;
import com.example.haoqisystem.request.*;
import com.example.haoqisystem.response.BaseResponse;
import com.example.haoqisystem.response.PageResult;
import com.example.haoqisystem.response.QuestionnaireResultResponse;
import com.example.haoqisystem.respository.QuestionNaireRepository;
import com.example.haoqisystem.respository.QuestionNaireRepository;
import com.example.haoqisystem.respository.TrainningPlanRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.*;

@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ ={@Autowired} )
public class QuestionNaireService {
    private final QuestionNaireRepository questionNaireRepository;

    //新增培训计划
    public BaseResponse<QuestionNaire> add(CreateQuestionNaireRequest request) {
        try{
            QuestionNaire naire=new QuestionNaire();
            BeanUtil.copyProperties(request,naire, CopyOptions.create().setIgnoreNullValue(true));
            return new BaseResponse<>(ConstUtil.CREATE_SUCCESS,true,questionNaireRepository.save(naire));
        }catch (Exception e){
            return new BaseResponse<>(e.toString(), false,null);
        }
    }

    //详情
    public BaseResponse<QuestionNaire> detail(Long id) {
        try{
            Optional<QuestionNaire> optionalQuestionNaire=questionNaireRepository.findById(id);
            if(!optionalQuestionNaire.isPresent()){
                return new BaseResponse<>("该调查问卷不存在！",false,null);
            }
            QuestionNaire naire=optionalQuestionNaire.get();
            return new BaseResponse<>(ConstUtil.QUERY_SUCCESS,true,naire);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //更新
    public BaseResponse<QuestionNaire> update(UpdateQuestionNaireRequest request) {
        try{
            Optional<QuestionNaire> optionalQuestionNaire=questionNaireRepository.findById(request.getId());
            if(!optionalQuestionNaire.isPresent()){
                return new BaseResponse<>("该调查问卷不存在！",false,null);
            }
            QuestionNaire naire=optionalQuestionNaire.get();
            BeanUtil.copyProperties(request,naire,CopyOptions.create().setIgnoreNullValue(true));
            return new BaseResponse<>(ConstUtil.UPDATE_SUCESS,true,questionNaireRepository.save(naire));
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //删除
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<String> delete(List<Long> ids) {
        if(ids.isEmpty()){
            return new BaseResponse<>(ConstUtil.DELETED_FALSE,false,"id列表不能为空");
        }
        List<QuestionNaire> list=questionNaireRepository.findAllById(ids);
        for(QuestionNaire naire:list){
            naire.setDeleted(true);
            questionNaireRepository.save(naire);
        }
        return new BaseResponse<>(ConstUtil.DELETED_SUCCESS,true,"查询成功！");
    }

    //查询列表
    public BaseResponse<PageResult<QuestionNaire>> queryList(QueryQuestionNaireRequest request) {
        try{
            Specification<QuestionNaire> specification=(root, query, builder) -> {
                List<Predicate> predicates=new ArrayList<>();
                //TODO:
                predicates.add(builder.equal(root.get("deleted"),request.isDeleted()));
                return builder.and(predicates.toArray(new Predicate[0]));
            };
            List<QuestionNaire> list=questionNaireRepository.findAll(specification);
            Collections.reverse(list);
            PageResult<QuestionNaire> page= PageUtil.getPage(list,request.getPageNum(),request.getPageSize());
            return new BaseResponse<>(ConstUtil.QUERY_SUCCESS,true,page);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //查询列表不分页
    public BaseResponse<List<QuestionNaire>> queryList1(Long id) {
        try{
            Specification<QuestionNaire> specification=(root, query, builder) -> {
                List<Predicate> predicates=new ArrayList<>();
                if(id!=null){
                    predicates.add(builder.equal(root.get("lectureId"),id));
                }
                predicates.add(builder.equal(root.get("deleted"),false));
                return builder.and(predicates.toArray(new Predicate[0]));
            };
            List<QuestionNaire> list=questionNaireRepository.findAll(specification);
            Collections.reverse(list);
            return new BaseResponse<>(ConstUtil.QUERY_SUCCESS,true,list);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //统计结果
    public BaseResponse<QuestionnaireResultResponse> findResult(Long lectureId) {
        try {
            Specification<QuestionNaire> specification=(root, query, builder) -> {
                List<Predicate> predicates=new ArrayList<>();
                predicates.add(builder.equal(root.get("lectureId"),lectureId));
                predicates.add(builder.equal(root.get("deleted"),false));
                return builder.and(predicates.toArray(new Predicate[0]));
            };
            QuestionnaireResultResponse response = new QuestionnaireResultResponse();
            List<QuestionNaire> questionNaires = questionNaireRepository.findAll(specification);
            float sumTeacher = 0;
            float sumLecture = 0;
            int i = 0;
            float[] teacherCounts = new float[6];
            float[] lectureCounts = new float[6];
            // 初始化teacherCounts数组为0
            for (int j = 0; j < teacherCounts.length; j++) {
                teacherCounts[j] = 0;
            }
            // 初始化lectureCounts数组为0
            for (int j = 0; j < lectureCounts.length; j++) {
                lectureCounts[j] = 0;
            }

            for (QuestionNaire questionNaire : questionNaires) {
                sumTeacher += questionNaire.getTeacherScore();
                sumLecture += questionNaire.getLectureScore();
                i += 1;
                // 统计分数段数量
                int teacherScore = questionNaire.getTeacherScore();
                int lectureScore=questionNaire.getLectureScore();
                teacherCounts[teacherScore]++;
                lectureCounts[lectureScore]++;
            }
            response.setTeacherScore(sumTeacher / i);
            response.setLectureScore(sumLecture / i);
            // 计算分数段占比
            Map<Integer, Float> teacherPercentages=new HashMap<>();
            Map<Integer, Float> lecturePercentages=new HashMap<>();
            for (int j = 0; j < 6; j++) {
                float teacherPercentage = (teacherCounts[j] / i)*100; // 计算占比
                float lecturePercentage=(lectureCounts[j]/i)*100;

                teacherPercentages.put(j,teacherPercentage);
                lecturePercentages.put(j,lecturePercentage);
            }
            response.setTeacherPercentages(teacherPercentages);
            response.setLecturePercentages(lecturePercentages);
            // 构建响应
            BaseResponse<QuestionnaireResultResponse> baseResponse = new BaseResponse<>();
            baseResponse.setData(response);
            // 其他设置...
            return baseResponse;
        } catch (Exception e) {
            return new BaseResponse<>(e.toString(),false,null);
        }
    }
}
